<?php
namespace app\common\model;
use x\Xbase;
class UserVip extends Xbase
{
    /**
     * 升级 - vip
     * @param [type] $user_id    [description]
     * @param [type] $level_id   [description]
     * @param [type] $pay_type   [description]
     * @param string $invitecode [description]
     * @param string $user_sign  [description]
     */
    public function add($user_id,$level_id,$pay_type,$invitecode,$user_sign=""){
        //if (!$invitecode) return $this->setError('请输入推荐关系');
        $userinfo = $this->db->find("user",$user_id);
        if(!$userinfo || (int)$userinfo['status'] !== 0) return $this->setError('用户不存在或被禁用');

        $levelinfo = $this->db->find("user_level_config",$level_id);
        if(!$levelinfo) return $this->setError('未配置的级别');
        if ($userinfo['level']!=0) return $this->setError('对不起，您已经成为云店或代理！');
        if ($levelinfo['level']!=1) return $this->setError('只能升级为vip云店');
        
        #推荐关系
        $s_id = 10000;
        if ($invitecode && $invitecode!="") {
            $s_userid = de_id($invitecode);
            $s_user = $this->db->find('user',$s_userid,'id,level');
            if (!$s_user) return $this->setError('错误的邀请码！');
            if (!$s_user['level']) return $this->setError('无效的邀请码！');
            if ($s_user['id']==$user_id) return $this->setError('邀请码不能为自己的！');
            $s_id = $s_user['id'];
        }

        $pay_money =  0;
        if(bcmul($userinfo['money'],100,2) < bcmul($levelinfo["money"],100,2)){
            $pay_money = $levelinfo["money"] - $userinfo['money'];
        }
        $order_no = com_order_no();
        $data = [
            "user_id" => $user_id,
            "s_id" => $s_id,
            "order_no" => $order_no,
            "befor_level" => $userinfo["level"],
            "after_level" => $levelinfo["level"],
            "money" => $levelinfo["money"],
            "pay_money" => $pay_money,
            "points" => $levelinfo['points'],
            "stock" => $levelinfo["stock"],
            "user_sign" => $user_sign,
            "pay_type" => $pay_type,
            "create_time" => time(),
        ];
        $rs = $this->db->insert("user_vip",$data);
        if($user_sign){
            $pic = [
                "pic" => $user_sign
            ];
            m('Attachment','xcom')->imgSure('user_vip',$rs,$pic);
        }
        if(!$rs) return $this->setError('生成订单失败');
        return $data;
    }

}
